package com.example.chengzhong.controller;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.InputStream;
import java.util.Timer;

public class ComPortReader {

    private static final String PORT_NAME = "COM1";
    private static final int BAUD_RATE = 1200;
    private static final int DATA_BITS = SerialPort.DATABITS_8;
    private static final int STOP_BITS = SerialPort.STOPBITS_1;
    private static final int PARITY = SerialPort.PARITY_NONE;

    private static SerialPort serialPort;
    private static InputStream inputStream;

    private static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        try {
            // 1. 获取串口标识
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(PORT_NAME);

            // 2. 打开串口并设置参数
            serialPort = (SerialPort) portIdentifier.open("ComReader", 2000);
            serialPort.setSerialPortParams(BAUD_RATE, DATA_BITS, STOP_BITS, PARITY);

            // 3. 注册事件监听器
            serialPort.addEventListener(new SerialPortListener());
            serialPort.notifyOnDataAvailable(true);

            // 4. 获取输入流
            inputStream = serialPort.getInputStream();

            System.out.println("串口连接成功，开始监听数据...");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void save(){
        Timer timer = new Timer();
    }

    // 串口事件监听类
    private static class SerialPortListener implements SerialPortEventListener {
        @Override
        public void serialEvent(SerialPortEvent event) {
            if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    byte[] buffer = new byte[1024*1024];
                    int len;
                    while ((len = inputStream.read(buffer)) > 0) {
                        String data = new String(buffer, 0, len);
                        sb.append(data);
                        if (data.endsWith("\n")) {
                            System.out.println("接收数据: " + sb);
                            sb = new StringBuilder();
                        }
//                        System.out.println("接收数据: " + data);
//                        if (data.contains("\n")){
//                            System.out.println("hahaha");
//                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
